import 'package:flutter/material.dart';
import 'package:flutter_app/2_advance/pages/book_case_page.dart';
import 'package:flutter_app/2_advance/pages/discover_page.dart';
import 'package:flutter_app/2_advance/pages/mine_page.dart';
import 'package:flutter_app/2_advance/pages/read_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;

  late List<Widget> _pageList;

  @override
  void initState() {
    // 没有好的办法懒加载
    // 只能在网络操作的时候不显示进度
    _pageList = [
      const ReadPage(),
      const BookCasePage(),
      const DiscoverPage(),
      const MinePage(),
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: _pageList,
      ),
      bottomNavigationBar: Theme(
        data: ThemeData(
          // 去掉水波纹效果
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
        ),
        child: BottomNavigationBar(
          // 将选中和未选中设置成相同大小即可
          selectedFontSize: 12,
          backgroundColor: Colors.white,
          elevation: 1,
          fixedColor: Colors.lightBlue,
          // 选中颜色
          type: BottomNavigationBarType.fixed,
          // 超过三个底部导航项时要设置类型，
          onTap: (int index) {
            setState(() => _currentIndex = index);
          },
          currentIndex: _currentIndex,
          // 当前选中索引
          items: [
            _barItem(Icons.home, '阅读', ''),
            _barItem(Icons.games, '书架', ''),
            _barItem(Icons.shop, '发现', ''),
            _barItem(Icons.person, '我的', '10'),
          ],
        ),
      ),
    );
  }

  // 显示未读数
  BottomNavigationBarItem _barItem(IconData icon, String label, String count) {
    return BottomNavigationBarItem(
      label: label,
      icon: Badge(
        backgroundColor: count.isEmpty ?  Colors.transparent : Colors.red,
        label: count.isEmpty ? null : Text(count),
        child: Icon(icon),
      ),
    );
  }
}
